﻿using System;
using System.Data;
using System.Web;
using System.Web.Caching;

namespace PMS.Utils
{
    public class DataCache
    {
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static object GetCache(string keyName)
        {
            return HttpRuntime.Cache.Get(keyName);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="obj"></param>
        public static void SetCache(string keyName, object obj)
        {
            HttpRuntime.Cache.Insert(keyName, obj);
        }

        /// <summary>
        /// 添加缓存并设置过期时间 ps:相对过期时间
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="obj"></param>
        /// <param name="timeOut"></param>
        public static void SetCache(string keyName, object obj, int timeOut)
        {
            HttpRuntime.Cache.Insert(keyName, obj, null, DateTime.Now.AddHours(timeOut), TimeSpan.Zero, CacheItemPriority.High, null);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="keyName"></param>
        public static void Remove(string keyName)
        {
            HttpRuntime.Cache.Remove(keyName);
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void Remove()
        {
            var data = HttpRuntime.Cache.GetEnumerator();
            while (data.MoveNext())
            {
                if (data.Key != null) HttpRuntime.Cache.Remove(data.Key.ToString());
            }
        }
    }
}